package com.zhiwei.common.util;

import lombok.SneakyThrows;
import sun.misc.BASE64Encoder;

import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.io.ByteArrayOutputStream;

/**
 * function 图片工具
 * author zhiwei.yang
 * time 2020-3-16-9:45
 */
public final class ImageUtil {

    /**
     * 图片转Base64编码
     * @return
     */
    @SneakyThrows
    public static String imageToBase64(BufferedImage bufferedImage){
        try (ByteArrayOutputStream baos = new ByteArrayOutputStream()) {
            ImageIO.write(bufferedImage, "png", baos);
            byte[] bytes = baos.toByteArray();
            BASE64Encoder encoder = new BASE64Encoder();
            String png_base64 = encoder.encodeBuffer(bytes).trim();
            return "data:image/png;base64,".concat(png_base64.replaceAll("[\r|\n]", ""));
        }

    }
}
